function Snake(el) {
    this.el = el    //保存地图对象
    this.len = 20   //蛇的每节长度
    this.SnakeObj = [
        { x: 3, y :2, color:'red', el:null},  //蛇头
        { x: 2, y :2, color:'blue', el:null}, // 蛇身
        { x: 1, y :2, color:'blue', el:null}  // 蛇的身体
    ]
    this.direction = 'right'

}
Snake.prototype.remove = function () {
    for(let i =0;i<this.SnakeObj.length; i++){
        if(this.SnakeObj[i].el){
            this.el.removeChild(this.SnakeObj[i].el)
        }
    }
}

Snake.prototype.create= function () {

    this.remove()

    for(let i =0;i<this.SnakeObj.length;i++){

        let divObj = document.createElement('div')
        divObj.style.width = this.len + 'px'
        divObj.style.height = this.len+ 'px'
        divObj.style.background = this.SnakeObj[i].color
        divObj.style.left = this.SnakeObj[i].x*this.len+'px'
        divObj.style.top  = this.SnakeObj[i].y*this.len+'px'
        divObj.style.position = 'absolute'

        //保存蛇节
        this.SnakeObj[i].el = divObj
        
        this.el.appendChild(divObj)


    }
}



// Snake.prototype.move =function () {
//     for (let i =0;i<this.SnakeObj.length;i++){
//         this.SnakeObj[i].x += 1
//     }
//     //重新创建
//     this.create()
// }
Snake.prototype.move = function () {
    for(let i =this.SnakeObj.length-1;i>0;i--){
        this.SnakeObj[i].x = this.SnakeObj[i-1].x
        this.SnakeObj[i].y = this.SnakeObj[i-1].y
    }

    switch(this.direction) {
        case 'top':
            this.SnakeObj[0].y -= 1
            break;
        case 'buttom':
            this.SnakeObj[0].y += 1
            break;
        case 'right':
            this.SnakeObj[0].x += 1
            break;
        case 'left':
            this.SnakeObj[0].x -=1
            break;
    }

    this.create()
    
}